package com.jsu.clubmanagementsystem.controller.activity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsu.clubmanagementsystem.common.BaseResponse;
import com.jsu.clubmanagementsystem.common.ErrorCode;
import com.jsu.clubmanagementsystem.common.PageQueryRequest;
import com.jsu.clubmanagementsystem.common.ResultUtils;
import com.jsu.clubmanagementsystem.constant.UserConstant;
import com.jsu.clubmanagementsystem.exception.BusinessException;
import com.jsu.clubmanagementsystem.model.dto.activity.ActivityQueryRequest;
import com.jsu.clubmanagementsystem.model.dto.activitymembership.ActivityMembershipQueryRequest;
import com.jsu.clubmanagementsystem.model.entity.Activity;
import com.jsu.clubmanagementsystem.model.entity.User;
import com.jsu.clubmanagementsystem.model.vo.activity.ActivityVO;
import com.jsu.clubmanagementsystem.model.vo.activity.ListActivityVO;
import com.jsu.clubmanagementsystem.model.vo.user.UserVO;
import com.jsu.clubmanagementsystem.service.activity.ActivityMembershipService;
import com.jsu.clubmanagementsystem.service.activity.ActivityService;
import com.jsu.clubmanagementsystem.service.user.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/activity")
public class ActivityController {

    @Resource
    private ActivityService activityService;

    @Resource
    private ActivityMembershipService activityMembershipService;

    @Resource
    private UserService userService;

    /**
     * 查看社团活动封装
     * @param activityId
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ActivityVO> getActivityVoById(long activityId, HttpServletRequest request) {
        if ( !activityService.isExist(activityId)) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "活动不存在");
        }
        // 检查登录状态
        User loginUser = userService.getLoginUser(request);

        Activity activity = activityService.getById(activityId);
        ActivityVO activityVO = activityService.getActivityVO(activity);
        return ResultUtils.success(activityVO);
    }

    /**
     * 查找社团活动封装 (分页）
     * @param queryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/vo")
    public BaseResponse<Page<ActivityVO>> listActivityVoByPage(@RequestBody ActivityQueryRequest queryRequest, HttpServletRequest request){
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }

        //1. 获取QueryWrapper
        QueryWrapper<Activity> queryWrapper = activityService.getQueryWrapper(queryRequest);

        //2. 处理Page
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        Page<Activity> page = activityService.page(new Page<>(current, pageSize), queryWrapper);
        Page<ActivityVO> voPage = activityService.getActivityVoPage(page);
        return ResultUtils.success(voPage);
    }

    /**
     * 查看活动成员表
     *
     * @param queryRequest 查询请求
     * @param request      HTTP请求
     * @return 成员分页数据
     */
    @PostMapping("/list/user")
    public BaseResponse<Page<UserVO>> listUserVoInActivityByPage(@RequestBody ActivityMembershipQueryRequest queryRequest, HttpServletRequest request) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        Long activityId = queryRequest.getActivityId();
        Long userId = queryRequest.getUserId();
        if (!activityService.isExist(activityId)) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "活动不存在");
        }
        if (userId != null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数错误");
        }

        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN) &&
                !activityMembershipService.isUserInActivity(loginUser.getId(), activityId)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限执行此操作");
        }

        Page<UserVO> userVOPage = activityService.listUserVoInActivityByPage(queryRequest);
        return ResultUtils.success(userVOPage);
    }

    /**
     * 查看用户参与的活动列表
     *
     * @param queryRequest 查询请求
     * @param request      HTTP请求
     * @return 活动分页数据
     */
    @PostMapping("/list/activity")
    public BaseResponse<Page<ActivityVO>> listActivityVoOfUserByPage(@RequestBody ActivityMembershipQueryRequest queryRequest, HttpServletRequest request) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        Long userId = queryRequest.getUserId();
        if( !userService.isExist(userId)){
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户不存在");
        }

        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN) &&
                !loginUser.getId().equals(userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限执行此操作");
        }

        Page<ActivityVO> activityVOPage = activityService.listActivityVoOfUserByPage(queryRequest);
        return ResultUtils.success(activityVOPage);
    }

    /**
     * 判断用户是否是该社团的成员
     *
     * @param queryRequest
     * @return
     */
    @PostMapping("/have-engaged")
    public BaseResponse<Boolean> isUserInActivity(@RequestBody ActivityMembershipQueryRequest queryRequest) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }

        Long userId = queryRequest.getUserId();
        Long activityId = queryRequest.getActivityId();
        if (!userService.isExist(userId) || !activityService.isExist(activityId)) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户或目标活动不存在");
        }
        return ResultUtils.success(activityMembershipService.isUserInActivity(userId, activityId));
    }

    /**
     * 获取所有活动
     * @return
     */
    @PostMapping("/list/all")
    public BaseResponse<Page<ListActivityVO>> getAllActivity(@RequestBody PageQueryRequest page){
        return ResultUtils.success(activityService.getAllActivity(page));
    }

    /**
     * 删除活动(及批量删除)
     */
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> delete(@RequestParam List<Long> ids){
        return ResultUtils.success(activityService.deleteActivitys(ids));
    }
}
